/*
 * @Description: 原文上传弹窗
 * @Author: Zzt
 * @Date: 2022-10-15 17:45:20
 * @LastEditTime: 2022-10-27 20:45:28
 */
import { UploadOutlined } from '@ant-design/icons';
import { debounce } from 'lodash';

import { Button, Col, Modal, Progress, Row, Typography, Upload } from 'antd';
import { useState } from 'react';
import { saveOriginFiles } from '@/api/standardizedDetection/detectionTask';
import { useStandardizedDetectionContext } from '../../contexts/StandardizedDetectionContext';
import { uploadResource } from '@/api/upload';

const UploadSip = (props: any) => {
  const { visible, onClose } = props;
  const { activeStandardized, updateStandardizedList, selectAT, selectFond } =
    useStandardizedDetectionContext();
  // 选中文件列表
  const [uploadList, setUploadList] = useState([]);
  // 上传文件按钮loading状态
  const [uploadLoading, setUploadLoading] = useState(false);
  // 上传进度
  const [uploadPercent, setUploadPercent] = useState(0);

  /**
   * @description: upload组件上传前钩子，处理选中的文件列表
   * @param {File} file
   */
  const beforeUpload = (file: File) => {
    setUploadList((state) => [...state, file]);
    return true;
  };

  const getFileUrl = (name: string, fileUrls: any): string => {
    return fileUrls.find((item: any) => item.name === name)?.url || '';
  };
  const onCancel = () => {
    onClose();
  };
  /**
   * @description: 上传选中的文件
   * @param {File[]} fileList
   */
  const uploadOriginalFunc = (fileList: File[]): void => {
    const formData = new FormData();
    fileList.forEach((file: File) => {
      formData.append('files', file);
    });

    uploadResource(formData, {
      timeout: 0,
      onUploadProgress: (progress: any) => {
        setUploadPercent(Number(((progress.loaded / progress.total) * 100).toFixed(1)));
      }
    }).then((res: any) => {
      const fileUrlObjs = res.data;
      const params: any = { id: activeStandardized.id };
      const realFileList = uploadList.map((file: File) => {
        return {
          fileName: file.name,
          filePath: file.webkitRelativePath.split('/').splice(1).join('/'),
          fileSize: file.size,
          fileUrl: getFileUrl(file.name, fileUrlObjs)
        };
      });

      params.originalAtt = {
        level: 0,
        realFileList,
        status: true
      };

      saveOriginFiles(params).then((res: any) => {
        updateStandardizedList(res.data);
      });
    });
  };
  return (
    <Modal
      visible={visible}
      className="upload-origin-dialog"
      // width={600}
      maskClosable={false}
      destroyOnClose
      title="EEP上传"
      onCancel={onCancel}
      footer={[
        <Button key="back" onClick={onCancel}>
          关闭
        </Button>,
        <Button key="submit" type="primary" onClick={onCancel}>
          保存
        </Button>
      ]}
    >
      <p>
        全宗:{selectFond.fondName} - 档案类型{''}:{selectAT.atName}
      </p>
      <div>
        <Row>
          <Col span={8}>
            <Typography.Paragraph strong>请上传EEP格式包</Typography.Paragraph>
          </Col>
          <Col span={6}>
            <Upload
              maxCount={1}
              accept=".eep,.EEP"
              beforeUpload={beforeUpload}
              fileList={[]}
              customRequest={debounce((value) => {
                setUploadLoading(false);
                uploadOriginalFunc(uploadList);
              })}
            >
              {uploadPercent > 0 && uploadPercent < 100 ? (
                <Button type="link" disabled>
                  点击上传
                </Button>
              ) : (
                <Button
                  type="link"
                  loading={uploadLoading}
                  onClick={() => {
                    setUploadList([]);
                    setUploadPercent(0);
                  }}
                >
                  点击上传
                </Button>
              )}
            </Upload>
          </Col>
        </Row>
        <Row>
          <Col span={4}>{uploadPercent > 0 && uploadPercent < 100 ? '正在上传' : ''}</Col>
          <Col span={17}>
            <Progress
              strokeColor={{
                '0%': '#108ee9',
                '100%': '#87d068'
              }}
              percent={uploadPercent}
              status={uploadPercent === 100 ? 'success' : 'active'}
            />
          </Col>
          <Col span={3}>
            {/* {uploadPercent > 0 && uploadPercent < 100 ? <Button type="link">取消</Button> : ''} */}
          </Col>
        </Row>
      </div>
    </Modal>
  );
};
export default UploadSip;
